package com.xuecheng.media.service.impl;

import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.commons.constants.CommonConstants;
import com.xuecheng.commons.constants.CourseConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.MediaDto;
import com.xuecheng.commons.model.dto.MediaQueryDto;
import com.xuecheng.commons.model.dto.PageRequest;
import com.xuecheng.commons.model.dto.VodUploadDto;
import com.xuecheng.commons.model.vo.*;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.media.config.VodTemplate;
import com.xuecheng.media.domain.Media;
import com.xuecheng.media.mappers.MediaMapper;
import com.xuecheng.media.service.MediaService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.web.exceptions.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 媒资信息 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-09-22
 */
@Service
public class MediaServiceImpl extends ServiceImpl<MediaMapper, Media> implements MediaService {

    @Autowired
    private VodTemplate template;

    //获取阿里云上传凭证
    @Override
    public ResponseResult<VodUploadVo> createToken(VodUploadDto dto) throws Exception {
        //1.获取标题和文件名
        String title = dto.getTitle();
        String fileName = dto.getFileName();
        if (StringUtils.isEmpty(title) || StringUtils.isEmpty(fileName)) {
            throw new BusinessException(ErrorCode.ERROR);
        }
        //2.调用阿里云工具类获取上传凭证
        CreateUploadVideoResponse response = template.createUploadVideo(title, fileName);
        //3.构造返回对象
        VodUploadVo vodUploadVo = new VodUploadVo();
        vodUploadVo.setRequestId(response.getRequestId());
        vodUploadVo.setUploadAddress(response.getUploadAddress());
        vodUploadVo.setUploadAuth(response.getUploadAuth());
        vodUploadVo.setUserId(AuthInfoHolder.getUserId().toString());
        vodUploadVo.setVideoId(response.getVideoId());
        return ResponseResult.okResult(vodUploadVo);
    }
    //刷新阿里云上传凭证
    @Override
    public ResponseResult<VodUploadVo> refreshToken(String videoId) throws Exception {
        //1.调用阿里云工具类获取上传凭证
        RefreshUploadVideoResponse response = template.refreshUploadVideo(videoId);
        //2.构造返回对象
        VodUploadVo vodUploadVo = new VodUploadVo();
        vodUploadVo.setRequestId(response.getRequestId());
        vodUploadVo.setUploadAddress(response.getUploadAddress());
        vodUploadVo.setUploadAuth(response.getUploadAuth());
        vodUploadVo.setUserId(AuthInfoHolder.getUserId().toString());
        vodUploadVo.setVideoId(response.getVideoId());
        return ResponseResult.okResult(vodUploadVo);
    }
    //保存媒资信息
    @Override
    public ResponseResult saveMedia(MediaDto dto) throws Exception {
        //1.将传入的数据转到实体类对象中
        Media media = BeanHelper.copyProperties(dto, Media.class);
        //2.补充基本参数
        media.setCompanyName(AuthInfoHolder.getAuthInfo().getCompanyName());
        media.setCreateDate(new Date());
        media.setStatus(CommonConstants.USING_FLAG.toString());
        media.setAuditStatus(CourseConstants.AUDIT_UNPAST_STATUS);
        //3.查询设置阿里云参数（url，timelength）
        GetPlayInfoResponse response = template.getPlayInfo(media.getFileId());
        List<GetPlayInfoResponse.PlayInfo> list = response.getPlayInfoList();
        GetPlayInfoResponse.PlayInfo playInfo = list.get(0);
        media.setTimelength(playInfo.getDuration());
        media.setUrl(playInfo.getPlayURL());
        //4.保存
        boolean save = this.save(media);
        if (!save) {
            throw new BusinessException(ErrorCode.ERROR);
        }
        return ResponseResult.okResult();
    }
    //分页查询媒资信息
    @Override
    public ResponseResult<MediaVo> findMediaList(PageRequest pageRequest, MediaQueryDto dto) {
        //1.设置分页条件
        Page<Media> page = new Page<>(pageRequest.getPageNo(), pageRequest.getPageSize());
        //2.设置查询条件
        LambdaQueryWrapper<Media> wrapper = new LambdaQueryWrapper<>();
        //审核状态
        //wrapper.eq(StringUtils.isNotEmpty(dto.getAuditStatus()), Media::getAuditStatus, dto.getAuditStatus());
        //文件名
        wrapper.like(StringUtils.isNotEmpty(dto.getFilename()), Media::getFilename, dto.getFilename());
        //文件类型
        wrapper.eq(StringUtils.isNotEmpty(dto.getType()),Media::getType,dto.getType());
        //3.查询
        Page<Media> mediaPage = this.page(page, wrapper);
        //4.返回
        //转化
        List<Media> list = mediaPage.getRecords();
        List<MediaVo> vos = BeanHelper.copyWithCollection(list,MediaVo.class);
        return PageResponseResult.okResult(mediaPage.getTotal(),vos);
    }
    //根据id删除媒资信息
    @Override
    public ResponseResult deleteById(Long mediaId) throws Exception {
        //1.查询媒资审核状态,判断是否可以删除
        Media media = this.getById(mediaId);
        String auditStatus = media.getAuditStatus();
        if (CourseConstants.AUDIT_PUBLISHED_STATUS.equals(auditStatus) ||
                CourseConstants.AUDIT_PASTED_STATUS.equals(auditStatus) ||
                CourseConstants.AUDIT_COMMIT_STATUS.equals(auditStatus)) {
            throw new BusinessException(ErrorCode.MEDIABINDERROR);
        }
        //2.先删除阿里云中存储的媒资，再对数据库逻辑删除
        template.deleteVideo(media.getFileId());
        boolean remove = this.removeById(media);
        if (!remove) {
            throw new BusinessException(ErrorCode.ERROR);
        }
        return ResponseResult.okResult(remove);
    }
    //根据id获取媒资URL地址
    @Override
    public ResponseResult<ResourceVo> findMediaUrl(Long mediaId) throws Exception {
        //1.根据mediaId获取media对象
        Media media = getById(mediaId);
        //2.获取阿里云id
        String id = media.getFileId();
        //3.调用工具类根据阿里云id从阿里云获取播放信息
        GetPlayInfoResponse playInfo = template.getPlayInfo(id);
        List<GetPlayInfoResponse.PlayInfo> playInfoList = playInfo.getPlayInfoList();
        GetPlayInfoResponse.PlayInfo info = playInfoList.get(0);
        //4.获取视频播放地址
        String url = info.getPlayURL();
        //5.创建返回对象
        ResourceVo vo = new ResourceVo();
        vo.setPlayUrl(url);
        return ResponseResult.okResult(vo);
    }
}
